const {Api} = require('../../mongodb/models')
const {getUserByCtx} = require('../../utils/common')

module.exports = [
	{
		path: '/api',
		method: 'post',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const reqData = ctx.request.body
			const isExist = await Api.findOne({userId:_id, method:reqData.method, url:reqData.url})
			if(isExist){
				ctx.response.body = {
					errCode: 1,
					errMsg: isExist.navId === reqData.navId ? '该API接口已存在' : '该API接口在其它目录已存在'
				}
			}else{
				const doc = await Api.create(Object.assign({userId: _id}, reqData))
				ctx.response.body = {
					errCode: doc ? 0 : -1,
					errMsg: doc ? '添加成功' : '添加失败',
					data: doc
				}
			}
		}
	},{
		path: '/api/:navId',
		method: 'get',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const docs = await Api.find({userId: _id, navId:ctx.params.navId})
			ctx.response.body = {
				errCode: docs ? 0 : -1,
				errMsg: docs ? 'request:success' : 'API接口列表获取失败',
				data: docs
			}
		}
	},{
		path: '/api/:id',
		method: 'put',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const reqData = ctx.request.body
			const res = await Api.updateOne({userId: _id, _id:ctx.params.id}, reqData)
			ctx.response.body = {
				errCode: res.nModified ? 0 : -1,
				errMsg: res.nModified ? '修改成功' : '修改失败',
				data: res
			}
		}
	},{
		path: '/api/:id',
		method: 'delete',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			const doc = await Api.deleteOne({userId: _id, _id: ctx.params.id})
			ctx.response.body = {
				errCode: doc ? 0 : -1,
				errMsg: doc ? '删除成功' : '删除失败',
				data: doc
			}
		}
	},{
		path: '/apiList',
		method: 'get',
		process: async (ctx, next) => {
			const docs = await Api.find({navId:ctx.query.navId})
			ctx.response.body = {
				errCode: docs ? 0 : -1,
				errMsg: docs ? 'request:success' : 'API接口列表获取失败',
				data: docs
			}
		}
	}
]